<template>
  <el-dialog
    top="30px"
    width="800px"
    title="修改项目信息"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <el-form size="small" ref="form" label-width="150px" :model="form" :rules="rules">
      <el-form-item label="贷款类型" prop="use_category">
        <el-input
          v-model="form.use_category"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="银行借款（授信）合同号" prop="ensurce_contract">
        <el-input
          v-model="form.ensurce_contract"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="受保企业" prop="customer_name">
        <el-input
          v-model="form.customer_name"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="企业性质" prop="org_class">
        <select-farm-org
          v-model="form.org_class"
          class="form-control-ml"
          @select="handleOrgClassSelect"
        ></select-farm-org>
      </el-form-item>
      <el-form-item label="登记所在地" prop="address_detail">
        <el-input
          v-model="form.address_detail"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属行业" prop="parent_industrial_class">
        <el-input
          v-model="form.parent_industrial_class"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="从业人数 （上一年末）" prop="emp_total">
        <el-input
          v-model="form.emp_total"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">人</span>
        </el-input>
      </el-form-item>
      <el-form-item label="上一年度营业收入" prop="sale_income">
        <el-input
          v-model="form.sale_income"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="上一年末资产总额" prop="assets_funds">
        <el-input
          v-model="form.assets_funds"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="被担保人划型（小微、三农/其他）" prop="warrantee_category">
        <el-input
          v-model="form.warrantee_category"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="担保项目投向" prop="project_invest">
        <el-input
          v-model="form.project_invest"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="扶持农村12个特色产业" prop="industrial_class">
        <el-input
          v-model="form.industrial_class"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="贷款银行（支行）" prop="bank_name">
        <el-input v-model="form.bank_name" class="form-control-ml" placeholder="请填写"></el-input>
      </el-form-item>
      <el-form-item label="银行确认放款金额" prop="confirm_reply_funds">
        <el-input
          v-model="form.confirm_reply_funds"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="贷款利率" prop="load_rate">
        <el-input
          v-model="form.load_rate"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="同期基准利率" prop="same_period_rate">
        <el-input
          v-model="form.same_period_rate"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="担保责任余额" prop="left_funds">
        <el-input
          v-model="form.left_funds"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="保证合同号" prop="gua_contract">
        <el-input
          v-model="form.gua_contract"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="担保责任开始日" prop="load_date">
        <el-date-picker
          class="form-control-ml"
          v-model="form.load_date"
          :clearable="false"
          placeholder="担保责任开始日"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="担保责任到期日" prop="load_end_date">
        <el-date-picker
          class="form-control-ml"
          v-model="form.load_end_date"
          :clearable="false"
          placeholder="担保责任到期日"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="担保费率" prop="warranty_rate">
        <el-input
          v-model="form.warranty_rate"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="银行分险比例" prop="risk_rate">
        <el-input
          v-model="form.risk_rate"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="当地政府是否建立风险补偿机制" prop="is_risk_mech">
        <c-radio-group
          v-model="form.is_risk_mech"
          :options="[
            { value: 1, label: '是' },
            { value: 0, label: '否' },
          ]"
        ></c-radio-group>
      </el-form-item>
      <el-form-item label="当地政府预算安排风险补偿金（如有）" prop="risk_comps_funds">
        <el-input
          v-model="form.risk_comps_funds"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="服务对象类型" prop="service_object_type">
        <c-select
          v-model="form.service_object_type"
          class="form-control-ml"
          number-key
          :options="enumServiceType"
        ></c-select>
      </el-form-item>
      <el-form-item label="带动当地建档立卡贫困户" prop="poverty_households">
        <el-input
          v-model="form.poverty_households"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">户</span>
        </el-input>
      </el-form-item>
      <el-form-item label="是否属于绿色扶贫产业项目" prop="is_poverty_project">
        <c-radio-group
          v-model="form.is_poverty_project"
          :options="[
            { value: 1, label: '是' },
            { value: 0, label: '否' },
          ]"
        ></c-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" class="form-control-ml" placeholder="请填写"></el-input>
      </el-form-item>
      <el-form-item label="公司放款流水号" prop="loan_number">
        <el-input
          v-model="form.loan_number"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSubmit" type="primary" class="btn-long" :loading="loading">
          保 存
        </el-button>
        <el-button @click="beforeClose" :disabled="loading">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { idCardValidate, licenseValidate } from '@vimi/utils-tool'
import { phoneValidator } from '@/common/plugins/validator'
import { convertFormErrMsg } from '@/common/plugins/tools/convert'
import { enumServiceType } from './mixins'

import SelectFarmOrg from '@/components/select/SelectFarmOrg'

export default {
  components: {
    SelectFarmOrg,
  },
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default: () => ({}),
    },
    reportType: {
      type: Number,
      default: 7,
    },
  },
  data() {
    const registerValidator = async (_, value, callback) => {
      if (!value) {
        return callback(new Error('请输入统一信用代码'))
      }

      if (!licenseValidate(value)) {
        return callback(new Error('统一信用代码格式错误'))
      }

      const isExist = await this.checkExist({
        'register_no.eq': value,
      })
      callback(isExist ? new Error('统一信用代码已存在') : void 0)
    }

    const idCardValidator = async (_, value, callback) => {
      if (!value) {
        return callback(new Error('请输入身份证号码'))
      }

      if (!idCardValidate(value)) {
        return callback(new Error('身份证号码错误'))
      }

      const isExist = await this.checkExist({
        'id_card.eq': value,
      })
      callback(isExist ? new Error('身份证号已存在') : void 0)
    }

    return {
      enumServiceType,

      loading: false,
      tableName: 'market_project',
      form: {},
      rules: {
        address_name_pro: { required: true, trigger: 'blur', message: '请填写归属省' },
        address_name_city: { required: true, trigger: 'blur', message: '请填写归属市' },
        address_name_county: { required: true, trigger: 'blur', message: '请填写归属县' },
        org_class: { required: true, trigger: 'change', message: '请选择客户类型' },
        customer_name: {
          required: true,
          trigger: 'blur',
          message: '请填写受保企业名称或贷款人姓名',
        },
        corp_name: { required: true, trigger: 'blur', message: '请填写受保企业联系人姓名' },
        corp_phone: [
          { required: true, trigger: 'blur', message: '请填写受保企业联系人电话' },
          { validator: phoneValidator, trigger: 'blur', message: '请填写正确的联系人电话' },
        ],
        is_cert_merge: { required: true, trigger: 'change', message: '请选择是否三证合一' },
        register_no: [
          { required: true, trigger: 'blur', message: '请填写统一社会信用代码' },
          { validator: registerValidator, trigger: 'blur' },
        ],
        id_card: [
          { required: true, trigger: 'blur', message: '请填写身份证号码' },
          { validator: idCardValidator, trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    tableId() {
      return this.formData.customer_related_id
    },
    isIndividual() {
      const { org_class: orgClass } = this.form
      return ['org_farmer', 'org_farm', 'org_large_breed'].includes(orgClass)
    },

    // 省担报表
    isProvinceGua() {
      return this.reportType === 5
    },
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      if (val) {
        this.init()
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    init() {
      this.form = { ...this.formData }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    beforeClose() {
      this.$emit('update:visible', false)
    },

    async checkExist(params) {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, {
          index: 1,
          size: 1,
          ...params,
        })
      )
      this.loading = false
      const data = (res && res.data && res.data.data) || []
      return data.length && data[0].customer_related_id === this.tableId
    },

    handleOrgClassSelect(name) {
      this.form.org_class_name = name
    },

    handleSubmit() {
      this.$refs.form.validate((valid, obj = {}) => {
        if (!valid) {
          this.$message.error(convertFormErrMsg(obj))
        } else {
          this.putData()
        }
      })
    },

    putData() {
      this.loading = true
      this.$api
        .updateData(this.$serviceName, this.tableName, this.tableId, this.form)
        .then(res => {
          this.$message.success(`修改成功！`)
          this.$emit('success', res)
          this.beforeClose()
        })
        .catch(() => {
          this.$message.success(`修改失败，请重试！`)
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
